package lgkj.meicqt20;

import android.app.Presentation;
import android.content.Context;
import android.content.Intent;
import android.hardware.display.DisplayManager;
import android.media.AudioManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Display;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

import butterknife.BindView;
import lgkj.meicqt20.bean.AdverBean;
import lgkj.meicqt20.bean.MessageEvent;
import lgkj.meicqt20.service.MyService;
import lgkj.meicqt20.ui.BaseActivity;
import lgkj.meicqt20.ui.CollegeActivity;
import lgkj.meicqt20.ui.LifefallowPlayActivity;
import lgkj.meicqt20.ui.MainDetailsActicity;
import lgkj.meicqt20.ui.ShopBoutiqueActivity;
import lgkj.meicqt20.ui.VideosActivity;
import lgkj.meicqt20.utils.AllKindsOfConstant;
import lgkj.meicqt20.utils.CommUtils;
import lgkj.meicqt20.utils.DbController;
import lgkj.meicqt20.utils.HttpUtils;
import lgkj.meicqt20.utils.SharedPreferencesUtils;
import lgkj.meicqt20.view.BannerVideoView;
import lgkj.meicqt20.view.CustomTextView;

public class MainActivity extends BaseActivity {
    @BindView(R.id.vd_shiping)
    BannerVideoView vdShiping;
    @BindView(R.id.tv_version)
    TextView tvVersion;
    @BindView(R.id.iv_details)
    ImageView ivDetails;
    @BindView(R.id.tv_mac_tips)
    TextView tvMacTips;
    @BindView(R.id.iv_right)
    ImageView ivRight;
    @BindView(R.id.mei_rong)
    ImageView meiRong;
    @BindView(R.id.jin_pin)
    ImageView jinPin;
    @BindView(R.id.xiu_xian)
    ImageView xiuXian;
    @BindView(R.id.shi_pin)
    ImageView shiPin;
    @BindView(R.id.ll_right)
    LinearLayout llRight;
    @BindView(R.id.jin_xi)
    ImageView jinXi;
    @BindView(R.id.iv_code)
    ImageView ivCode;
    private boolean isNetWord = true;
    private Handler mHandler;
    private boolean isleft = false;
    private AudioManager audioManager;
    private boolean isDealOrder;
    private int position = 1;
    private Map<Integer, ImageView> imageViews = new HashMap();
    private DbController dbController;
    private Class startClass[] = {CollegeActivity.class, ShopBoutiqueActivity.class, LifefallowPlayActivity.class, VideosActivity.class};
    private int x = 0;

    private List<String> urls = new ArrayList<>();
    public static String adTexts = "";
    List<AdverBean> adverBeans;

    @Override
    public int setContentView() {
        return R.layout.activity_main;
    }

    @Override
    public void init() {
        getlist();
        audioManager = (AudioManager) getSystemService(AUDIO_SERVICE);
        postUi();
        getRightImg();
        isRightShow();
        statLocation();
    }

    private void initDifferent() {
        DisplayManager manager = (DisplayManager) getSystemService(Context.DISPLAY_SERVICE);
        Display[] displays = manager.getDisplays();
        DifferentDislay differentDislay = new DifferentDislay(this, displays[1]);
        differentDislay.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
        differentDislay.show();
        vdShiping.play();
        vdShiping.setLevel(true);
    }

    private void getlist() {
        dbController = new DbController(MainActivity.this);
        adverBeans = dbController.searchAll();
//        advertlistBean.setData(adverBeans);
        Log.i(TAG, "DbController: " + adverBeans.size());
    }

    @Override
    public void initData() {
        startService(new Intent(this, MyService.class));
        EventBus.getDefault().register(this);
        ivDetails.setEnabled(isleft);
        HttpUtils.getQRCode(MainActivity.this, ivCode);
        erweimaTime();
        imageViews.put(1, meiRong);
        imageViews.put(2, jinPin);
        imageViews.put(3, xiuXian);
        imageViews.put(4, shiPin);
        jinPin.setEnabled(false);
        xiuXian.setEnabled(false);
        shiPin.setEnabled(false);
        sharedPreferencesUtils = new SharedPreferencesUtils(MainActivity.this);


    }

    @Override
    protected void onResume() {
        super.onResume();
        isDealOrder = true;
        initDifferent();
        MessageEvent messageEvent = new MessageEvent();
        messageEvent.setMessage(vdShiping.getmCurPlay() + "");
        messageEvent.setTagName("completionListener");
        EventBus.getDefault().post(messageEvent);
        Log.w(TAG, "send:getmCurPlay: " + vdShiping.getmCurPlay());
        vdShiping.setLevel(isDealOrder);
    }

    @Override
    protected void onPause() {
        super.onPause();
        isDealOrder = false;
        vdShiping.setLevel(isDealOrder);
    }


    /**
     * 右边广告
     */
    private void isRightShow() {
        TimerTask task = new TimerTask() {
            @Override
            public void run() {
                Message message = new Message();
                message.what = 2;
                x++;
                mHandler.sendMessage(message);
            }
        };
        Timer timer = new Timer();
        long delay = 0;
        long intevalPeriod = 2 * 60 * 1000;
        timer.scheduleAtFixedRate(task, delay, intevalPeriod);
    }

    /**
     * 7c:c7:09:2e:60:5c
     * https://md.05948166.com/meidian/index.php/home/barbershopdm/get_barbershop_dm?user=&tel=&ver=2.62&mac=38:a2:8c:6b:1c:6e
     */
    private void getRightImg() {
        Map<String, String> params = new HashMap<>();
        HttpUtils.getHttp(params, AllKindsOfConstant.getRightImg, new HttpUtils.HttpCallBack() {
            @Override
            public void successHttp(JSONObject jsonObject, int id) {
                try {
//                    urls.add("http://img1.imgtn.bdimg.com/it/u=1098644192,2325626771&fm=27&gp=0.jpg");
                    for (int i = 0; i < jsonObject.getJSONArray("data").length(); i++) {
                        urls.add(jsonObject.getJSONArray("data").getJSONObject(i).getString("url"));
                    }
//                    urls.add("http://img0.imgtn.bdimg.com/it/u=1179507070,172128662&fm=27&gp=0.jpg");
                    Log.i(TAG, "右边广告:" + urls.toString());
                    rightShowX = urls.size();
                    rightShowSlide();
//                        Glide.with(FirstActivity.this).load(Constant.loadImage(url)).diskCacheStrategy(DiskCacheStrategy.ALL).error(R.mipmap.defult_right).into(ivRight);
                } catch (JSONException e) {
                    ivRight.setBackgroundResource(R.mipmap.defult_right);
                }
            }

            @Override
            public void errorHttp(String msg) {
                ivRight.setBackgroundResource(R.mipmap.defult_right);
            }
        });
        HttpUtils.getPuzzle(params);
    }

    private int rightShowX = 0;

    /**
     * 右边广告
     */
    private void rightShowSlide() {
        TimerTask task = new TimerTask() {
            @Override
            public void run() {
                Message message = new Message();
                message.what = 3;
                rightShowX++;
                mHandler.sendMessage(message);
            }
        };
        Timer timer = new Timer();
        long intevalPeriod = 30 * 1000;
        if (urls.size() > 0) {
            intevalPeriod = (120 / urls.size()) * 1000;
        }
        timer.scheduleAtFixedRate(task, intevalPeriod, intevalPeriod);
    }


    private void getAdText() {
        adTexts = "";
        SimpleDateFormat df = new SimpleDateFormat("yyyyMMdd");//设置日期格式
        String token = "OneBase" + df.format(new Date()) + "l2V|gfZp{8`;jzR~6Y1_";
        String access_token = CommUtils.md5Password(token);
        Map<String, String> params = new HashMap<>();
        params.put("access_token", access_token);
        HttpUtils.getHttp(params, AllKindsOfConstant.advertList, new HttpUtils.HttpCallBack() {
            @Override
            public void successHttp(JSONObject jsonObject, int id) {
                try {
                    JSONArray jsonArray = jsonObject.getJSONArray("data");
                    for (int i = 0; i < jsonArray.length(); i++) {
                        adTexts += jsonArray.getJSONObject(i).getString("content") + "            ";
                    }
                    Log.i(TAG, "successHttp: " + adTexts);
                } catch (JSONException e) {
                    Log.i(TAG, "successHttp: " + e.getMessage());
                }
            }

            @Override
            public void errorHttp(String msg) {
                ivRight.setBackgroundResource(R.mipmap.defult_right);
            }
        });
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void Event(MessageEvent messageEvent) {
        Log.i(TAG, "socket: " + messageEvent.toString());
        switch (messageEvent.getTagName()) {
            case "control":
                ivRight.setVisibility(View.GONE);
                llRight.setVisibility(View.VISIBLE);
                dealOrder(messageEvent.getMessage());
                break;
            case "newAdvertlist":
                break;
            case "leave":
                boolean homeback = sharedPreferencesUtils.getParam("homeback");
                Log.i(TAG, "Event: " + homeback);
                if (homeback) {
                    if (activitiesList.size() > 0) {
                        for (int i = 0; i < activitiesList.size(); i++) {
                            if (activitiesList.get(i) != null) {
                                activitiesList.get(i).finish();
                                sharedPreferencesUtils.setParam("homeback", true);
                                //关闭
                                Log.i(TAG, "关闭这个activity成功~：  " + AllKindsOfConstant.activitiesList.get(i).getLocalClassName());
                            }
                        }
                    }
                }
                break;
            case "voice_add":
                audioManager.adjustStreamVolume(AudioManager.STREAM_MUSIC, AudioManager.ADJUST_RAISE, AudioManager.FLAG_SHOW_UI);
                break;
            case "voice_less":
                audioManager.adjustStreamVolume(AudioManager.STREAM_MUSIC, AudioManager.ADJUST_LOWER, AudioManager.FLAG_SHOW_UI);
                break;
        }
    }

    private void dealOrder(String order) {
        if (isDealOrder) {
            switch (order) {
                case "up":
                    if (position != 1 && !isleft) {
                        imageViews.get(position).setEnabled(false);
                        imageViews.get(position - 1).setEnabled(true);
                        position -= 1;
                    }
                    break;
                case "down":
                    if (position != 4 && !isleft) {
                        imageViews.get(position).setEnabled(false);
                        imageViews.get(position + 1).setEnabled(true);
                        position += 1;
                    }
                    break;
                case "left":
                    isleft = true;
                    break;
                case "right":
                    isleft = false;
                    break;
                case "sure":
                    Log.w(TAG, "sure:getmCurPlay: " + vdShiping.getmCurPlay() + "");
                    if (isleft) {
                        AdverBean adverBean = dbController.searchByWhere((vdShiping.getmCurPlay()) + "");
                        Log.w(TAG, "BannerVideoView: " + adverBean.toString());
                        Intent intent = new Intent(MainActivity.this, MainDetailsActicity.class);
                        if (adverBean != null) {
                            intent.putExtra("video_id", adverBean.getAd_id());
                        }
                        Log.i(TAG, "dealOrder: " + adverBean.getAd_id());
                        startActivity(intent);
                        isDealOrder = false;
                    } else {
                        if (position < 5) {
                            startActivity(new Intent(MainActivity.this, startClass[(position - 1)]));
                            isDealOrder = false;

                        }
                    }
                    vdShiping.setLevel(isDealOrder);

            }
            if (isleft) {
                meiRong.setEnabled(false);
                jinPin.setEnabled(false);
                xiuXian.setEnabled(false);
                shiPin.setEnabled(false);
            } else {
                imageViews.get(position).setEnabled(true);
            }
            ivDetails.setEnabled(isleft);
        }
    }

    private void erweimaTime() {
        TimerTask task = new TimerTask() {
            @Override
            public void run() {
                Message message = new Message();
                message.what = 1;
                mHandler.sendMessage(message);
                isNetWord = CommUtils.startPing();
            }
        };
        Timer timer = new Timer();
        long intevalPeriod = 5 * 1000;
        timer.scheduleAtFixedRate(task, 0, intevalPeriod);
    }

    private void postUi() {
        mHandler = new Handler() {
            public void handleMessage(Message msg) {
                Log.i(TAG, "handleMessage: " + msg.what);
                if (msg.what == 1) {
//                Log.i(TAG, "handleMessage: "+ (!tv_guanggao.getIsMarguee() && adTexts != null && adTexts.length() > 0));
//                if (!tv_guanggao.getIsMarguee() && adTexts != null && adTexts.length() > 0) {
//                    tv_guanggao.setVisibility(View.VISIBLE);
//                    tv_guanggao.setTxt(adTexts);
//                    tv_guanggao.startScroll();
//                }
                    if (isNetWord) {
                        HttpUtils.getQRCode(MainActivity.this, ivCode);

                    } else {
                        ivCode.setImageResource(R.mipmap.not_network);
                    }
                } else if (msg.what == 2) {
                    getAdText();
                    if (x % 3 == 2) {
                        ivRight.setVisibility(View.VISIBLE);
                        llRight.setVisibility(View.GONE);
                    } else {
                        ivRight.setVisibility(View.GONE);
                        llRight.setVisibility(View.VISIBLE);
                    }
                    Log.d(TAG, "isRightShow: " + x + "," + x % 3);
                } else if (msg.what == 3) {
                    int y = 0;
                    if (urls.size() > 0) {
                        String url = "";
                        y = rightShowX % urls.size();
                        try {
                            Log.i(TAG, "handleMessage: " + ",(" + rightShowX + "% " + y + "),imgs:" + y);
                            url = urls.get(y);
                        } catch (Exception e) {
                            Log.e(TAG, "超出数组:" + e.getMessage());
                            url = urls.get(0);
                        } finally {
                            Log.e(TAG, url);
                            if (MainActivity.this != null) {
                                CommUtils.LoadImage(MainActivity.this, ivRight, url, 0);
                            }
                        }
                    }
                }
            }
        };
    }


    public class DifferentDislay extends Presentation {
        private static final String TAG = "DifferentDislay";
        ImageView ivImg;
        private Context context;
        private CustomTextView tv_guanggao;
        private TextView textView;

        public DifferentDislay(Context outerContext, Display display) {
            super(outerContext, display);
            this.context = outerContext;
        }

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main1);
            ivImg = findViewById(R.id.iv_img);
            textView = findViewById(R.id.tv_tips);
            tv_guanggao = findViewById(R.id.tv_guanggao);
            if (adverBeans != null && adverBeans.size() > 0) {
                String url = adverBeans.get(0).getAd_cover();
                CommUtils.LoadImage(context, ivImg, url, 0);
            }
            Log.i(TAG, "onCreate: " + vdShiping.getmCurPlay());
            guanggao();
        }

        int x = 1;

        @Subscribe(threadMode = ThreadMode.MAIN)
        public void Event(MessageEvent messageEvent) {
            if (("completionListener").equals(messageEvent.getTagName())) {
                Log.w(TAG, "get:getmCurPlay: " + messageEvent.toString());
                startText();
                x++;
                String positoinStr = messageEvent.getMessage();
                String url;
                try {
                    int postion = Integer.parseInt(positoinStr);
                    url = adverBeans.get(postion).getAd_cover();
                    Log.i(TAG, "Event: " + adverBeans.get(postion).toString());
                    textView.setText(postion + "");
                } catch (Exception e) {
                    Log.e(TAG, "Event: " + e.getMessage());
                    url = "http://zxpic.imtt.qq.com/zxpic_imtt/2019/02/12/0910/originalimage/091410_2837810435_1_640_456.jpg";
                }
                Log.i(TAG, "Event: " + url);
                CommUtils.LoadImage(context, ivImg, url, 0);
            }
        }

        private void startText() {
            Log.i(TAG, "handleMessage: " + (!tv_guanggao.getIsMarguee() && adTexts != null && adTexts.length() > 0));
            if (!tv_guanggao.getIsMarguee() && adTexts != null && adTexts.length() > 0) {
                tv_guanggao.setVisibility(View.VISIBLE);
                tv_guanggao.setTxt(adTexts);
                tv_guanggao.startScroll();
            }
        }

        @Override
        protected void onStop() {
            super.onStop();
            EventBus.getDefault().unregister(this);
        }

        @Override
        protected void onStart() {
            super.onStart();
            EventBus.getDefault().register(this);
        }

        private void guanggao() {
            new Thread() {
                public void run() {
                    tv_guanggao.init(getWindowManager());
                    tv_guanggao.startScroll();
                    if (!"".equals(adTexts)) {
                        tv_guanggao.setTxt(adTexts);
                    }
                    tv_guanggao.setOnMargueeListener(new CustomTextView.OnMargueeListener() {
                        @Override
                        public void onRollOver() {
                            Log.i(TAG, "onRollOver: 滚动完毕");
//                        Toast.makeText(FirstActivity.this, "滚动完毕" + tv_guanggao.getIsMarguee(), Toast.LENGTH_SHORT).show();
                            if (tv_guanggao.getTxt().equals(adTexts)) {
                                adTexts = "";
                            }
                        }
                    });
                    Log.i(TAG, "mainMethod: " + tv_guanggao.getIsMarguee());
                }
            }.start();  //开启一个线程
        }
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
}
